package com.sxsihe.heartmate;

import android.app.*;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.*;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.usb.UsbManager;
import android.os.*;
import android.util.Log;
import android.view.*;
import android.widget.*;
import com.ant.liao.GifView;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.sxsihe.heartmate.view.TimePopupWindow;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DeviceView extends FrameLayout implements RadioGroup.OnCheckedChangeListener,View.OnClickListener {
    private FragmentManager fragmentManager;
    View view;
    TextView bluetooth_title;
    ImageView btn_bluetooth,btn_usb,back_icon;
    GifView refresh_icon;
    BluetoothAdapter btAdapt;
    CustomAdapter deviceAdapter;
    ListView lvBTDevices;
    List<ItemEntity> lstDevices = new ArrayList<ItemEntity>();
    int clickIndex;
    MainHandler handler ;
    String address ;
    int devType =0;
    List<UsbSerialDriver> drivers;
    private class MainHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0: {
//                    dialog.show();
                    break;
                }
                case 1: {
//                    dialog.dismiss();
                    break;
                }
                case 2: {
                    if(devType==0){
                        if(drivers.size()>0) {
                            showSerialDataActivity(drivers.get(0).getPorts().get(0));
                        }
                    }else if (devType==1){
                        Intent intent = new Intent(DeviceView.this.getContext(), RealTimeActivity.class);
                        System.out.println("address:"+address);
                        intent.putExtra("address",address);
//                        intent.putExtra("duration",duration);
                        int requestCode = 0;
                        ((Activity)DeviceView.this.getContext()).startActivityForResult(intent, requestCode);
                    }
                    break;
                }
                case 3: {
                    searchDevice();
                    refresh_icon.showAnimation();
                    break;
                }
                default:
                    break;
            }
        }
    }

    public DeviceView(Context context) {
        super(context);
        if (Integer.parseInt(Build.VERSION.SDK) >= 9) {
            this.setOverScrollMode(View.OVER_SCROLL_NEVER);
        }
        handler = new MainHandler();
        view = LayoutInflater.from(context).inflate(R.layout.main_tab_device, this);
        btn_usb = (ImageView)view.findViewById(R.id.btn_usb);
        btn_bluetooth = (ImageView)view.findViewById(R.id.btn_bluetooth);
        btAdapt = BluetoothAdapter.getDefaultAdapter();

        IntentFilter intent = new IntentFilter();
        intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果
        intent.addAction(BluetoothDevice.ACTION_NAME_CHANGED);// 用BroadcastReceiver来取得搜索结果
        intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        this.getContext().registerReceiver(searchDevices, intent);
        btn_usb.setOnClickListener(this);
        btn_bluetooth.setOnClickListener(this);
    }

    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }

    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
//        this.getContext().unregisterReceiver(searchDevices);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
//        FragmentTransaction transaction = fragmentManager.beginTransaction();
//        Fragment fragment = FragmentFactory.getInstanceByIndex(checkedId);
//        transaction.replace(R.id.testcontent, fragment,"fragment");
//        transaction.commit();
    }

//    public void toggleBluetooth(boolean flag){
//        if(btAdapt.isEnabled()) {
//            return;
//        }
//        if(flag){
//            btAdapt.enable();
//        }else{
//            btAdapt.disable();
//        }
//    }

    public boolean openBluetooth() {
        return btAdapt.isEnabled() || btAdapt.enable();
    }

    public boolean closeBluetooth() {
        return !btAdapt.isEnabled() || btAdapt.disable();
    }

    public void searchDevice(){
        if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启
            openBluetooth();
        }
        if (btAdapt.isDiscovering())
            btAdapt.cancelDiscovery();
        lstDevices.clear();
        if(deviceAdapter!=null) {
            deviceAdapter.notifyDataSetChanged();
            lvBTDevices.invalidateViews();
        }
        btAdapt.startDiscovery();
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.back_icon:
                this.removeViewAt(1);
                this.invalidate();
                btn_usb.setOnClickListener(this);
                btn_bluetooth.setOnClickListener(this);
                break;
            case R.id.bluetooth_title:
                Message msg = handler.obtainMessage();
                msg.what = 3;
                handler.sendMessage(msg);
                break;
            case R.id.btn_bluetooth:
                if(!openBluetooth())
                    return;
                Message _msg = handler.obtainMessage();
                _msg.what = 3;
                handler.sendMessageDelayed(_msg,3000);
                View bluetooth_list = LayoutInflater.from(this.getContext()).inflate(R.layout.device_bluetooth_list, this);
                this.getParent().bringChildToFront(bluetooth_list);
                lvBTDevices = (ListView) bluetooth_list.findViewById(R.id.lvBTDevices);
                back_icon = (ImageView) bluetooth_list.findViewById(R.id.back_icon);
                back_icon.setOnClickListener(this);
                refresh_icon = (GifView) bluetooth_list.findViewById(R.id.refresh_icon);
                refresh_icon.setGifImage(R.drawable.refresh);
                refresh_icon.showCover();
//                refresh_icon.setOnClickListener(this);
                bluetooth_title = (TextView) bluetooth_list.findViewById(R.id.bluetooth_title);
                bluetooth_title.setOnClickListener(this);


                deviceAdapter = new CustomAdapter(this.getContext(), lstDevices);
                lvBTDevices.setAdapter(deviceAdapter);

                lvBTDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                            long arg3) {
                        DeviceView.this.getContext().unregisterReceiver(searchDevices);

                        clickIndex = arg2;
                        if(btAdapt.isDiscovering())
                            btAdapt.cancelDiscovery();
                        ItemEntity itemEntity = (ItemEntity) deviceAdapter.getItem(clickIndex);
                        address = itemEntity.getAddress();
                        BluetoothDevice btDev = btAdapt.getRemoteDevice(address);
                        try {
                            Boolean returnValue = false;
                            if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
                                //利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);
                                Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
                                Log.d("BlueToothTestActivity", "开始配对");
                                returnValue = (Boolean) createBondMethod.invoke(btDev);
                            }else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){
                                devType = 1;
//                                showTimeWindow();
                                startIntent();
                            }
                        }
                        catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                btn_usb.setOnClickListener(null);
                btn_bluetooth.setOnClickListener(null);
                break;
            case R.id.btn_usb:
                devType =0;
                UsbManager mUsbManager = (UsbManager) this.getContext().getSystemService(Context.USB_SERVICE);
                 drivers =
                        UsbSerialProber.getDefaultProber().findAllDrivers(mUsbManager);
                if(drivers.size()>0) {
                    devType = 0;
                    startIntent();
//                    showTimeWindow();
//                    showSerialDataActivity(drivers.get(0).getPorts().get(0));
                }else{
                    final AlertDialog myDialog = new AlertDialog.Builder(getContext()).create();
                    myDialog.show();
                    myDialog.getWindow().setContentView(R.layout.serial_warning);

                    myDialog.getWindow()
                            .findViewById(R.id.confirm)
                            .setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    myDialog.dismiss();
                                }
                            });
                }
                break;
            case R.id.btn_1min:
//                startIntent(600÷0);
                popWindow.dismiss();
                break;
            case R.id.btn_3min:
//                startIntent(180000);
                popWindow.dismiss();
                break;
            case R.id.btn_no_limit:
//                startIntent(0);
                popWindow.dismiss();
                break;
        }
    }

    TimePopupWindow popWindow;
    public void showTimeWindow(){
        if(popWindow!=null&&popWindow.isShowing()){
            return;
        }
        popWindow = new TimePopupWindow(this.getContext(), this);
        popWindow.showAtLocation(this, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }




    public void startIntent(){
        Message msg = handler.obtainMessage();
        msg.what = 2;
//        msg.getData().putInt("duration", duration);
        handler.sendMessage(msg);
    }

//    Runnable r = new Runnable() {
//        @Override
//        public void run() {
//            if(btAdapt.isDiscovering())
//                btAdapt.cancelDiscovery();
//            ItemEntity itemEntity = (ItemEntity) deviceAdapter.getItem(clickIndex);
//            String address = itemEntity.getAddress();
//            BluetoothDevice btDev = btAdapt.getRemoteDevice(address);
//            try {
//                Boolean returnValue = false;
//                if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
//                    //利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);
//                    Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
//                    Log.d("BlueToothTestActivity", "开始配对");
//                    returnValue = (Boolean) createBondMethod.invoke(btDev);
//                }else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){
//                    startIntent(address);
//                }
//            }
//            catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    };

    class CustomAdapter extends BaseAdapter {

        private Context mContext;
        private List<ItemEntity> mData;
        private LayoutInflater mLayoutInflater;

        public CustomAdapter(Context pContext, List<ItemEntity> pData) {
            mContext = pContext;
            mData = pData;
            mLayoutInflater = LayoutInflater.from(mContext);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // 常见的优化ViewHolder
            ViewHolder viewHolder = null;
            if (null == convertView) {
                convertView = mLayoutInflater.inflate(R.layout.bluetooth_listview_item, null);
                viewHolder = new ViewHolder();
//                if(position%2==0){
//                    convertView.setBackgroundColor(Color.parseColor("#F5F5F5"));
//                }else{
//                    convertView.setBackgroundColor(Color.parseColor("#FFFFFF"));
//                }
                viewHolder.description = (TextView) convertView.findViewById(R.id.description);
                viewHolder.isPaired = (TextView) convertView.findViewById(R.id.is_paired);
//                viewHolder.address = (TextView) convertView.findViewById(R.id.address);
//                viewHolder.operation = (ImageView) convertView.findViewById(R.id.operation);
                viewHolder.bluetooth_status = (ImageView) convertView.findViewById(R.id.bluetooth_status);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            // 获取数据
            ItemEntity itemEntity = (ItemEntity) getItem(position);
            viewHolder.description.setText(itemEntity.getDescription());

            if(itemEntity.isPaired){
                viewHolder.isPaired.setText("已配对");
                viewHolder.bluetooth_status.setImageResource(R.drawable.bluetooth_paired);
            }else{
                viewHolder.isPaired.setText("未配对");
                viewHolder.bluetooth_status.setImageResource(R.drawable.bluetooth_unpaired);
            }


            return convertView;
        }

        @Override
        public int getCount() {
            if (null != mData) {
                return mData.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            if (null != mData && position < getCount()) {
                return mData.get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }


        /**
         * 判断是否需要显示标题
         *
         * @param position
         * @return
         */
        private boolean needTitle(int position) {
            // 第一个肯定是分类
            if (position == 0) {
                return true;
            }

            // 边界处理
            if (position < 0) {
                return false;
            }

            // 当前  // 上一个
            ItemEntity currentEntity = (ItemEntity) getItem(position);
            ItemEntity previousEntity = (ItemEntity) getItem(position - 1);
            if (null == currentEntity || null == previousEntity) {
                return false;
            }

            return true;
        }

        private class ViewHolder {
             TextView description;
            TextView address;
            TextView isPaired;
            ImageView bluetooth_status;
            ImageView operation;
         }
    }
    class ItemEntity implements Comparable<ItemEntity>{
        private String title;
        private String description;
        private String address;
        private int type;
        private boolean isPaired;
        private boolean isTitle;

        public ItemEntity(String title, String description, String address,boolean isPaired, int type,boolean isTitle) {
            this.title = title;
            this.description = description;
            this.address = address;
            this.isPaired = isPaired;
            this.type = type;
            this.isTitle = isTitle;
        }

        public boolean isPaired() {
            return isPaired;
        }

        public void setIsPaired(boolean isPaired) {
            this.isPaired = isPaired;
        }

        public boolean isTitle() {
            return isTitle;
        }

        public void setIsTitle(boolean isTitle) {
            this.isTitle = isTitle;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }

        @Override
        public int compareTo(ItemEntity another) {
            return this.getTitle().hashCode()-another.getTitle().hashCode();
        }

    }

    private BroadcastReceiver searchDevices = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            BluetoothDevice device = null;
            // 搜索设备时，取得设备的MAC地址
            if (BluetoothDevice.ACTION_FOUND.equals(action)||BluetoothDevice.ACTION_NAME_CHANGED.equals(action)) {
                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                    ItemEntity itemEntity = new ItemEntity("已配对", device.getName(), device.getAddress(),true, device.getBluetoothClass().getDeviceClass(),false);
                    boolean isAdd = false;
                    for(ItemEntity ie : lstDevices){
                        if(ie.getAddress().equals(device.getAddress())){
                            isAdd = true;
                        }
                    }
                    if (!isAdd)// 防止重复添加
                        lstDevices.add(itemEntity); // 获取设备名称和mac地址
                }

                if (device.getBondState() == BluetoothDevice.BOND_NONE) {
                    int type = BluetoothClass.Device.Major.UNCATEGORIZED;

                    if(device.getBluetoothClass()!=null){
                        type = device.getBluetoothClass().getMajorDeviceClass();
                    }
                    ItemEntity itemEntity = new ItemEntity("未配对",device.getName(),device.getAddress(),false,type,false);
                    boolean isAdd = false;
                    for(ItemEntity ie : lstDevices){
                        if(ie.getAddress().equals(device.getAddress())){
                            isAdd = true;
                        }
                    }
                    if (!isAdd)// 防止重复添加
                        lstDevices.add(itemEntity); // 获取设备名称和mac地址
                }
                Collections.sort(lstDevices);
                if(deviceAdapter!=null) {
                    deviceAdapter.notifyDataSetChanged();
                    lvBTDevices.invalidateViews();
                }
            }else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                switch (device.getBondState()) {
                    case BluetoothDevice.BOND_BONDING:
                        Log.d("BlueToothTestActivity", "正在配对......");
                        break;
                    case BluetoothDevice.BOND_BONDED:
                        Log.d("BlueToothTestActivity", "完成配对");
                        for(ItemEntity item: lstDevices){
                            if(item.getAddress().equals(device.getAddress())){
                                item.setIsPaired(true);
                            }
                        }
                        deviceAdapter.notifyDataSetChanged();
                        lvBTDevices.invalidateViews();
                        break;
                    case BluetoothDevice.BOND_NONE:
                        Log.d("BlueToothTestActivity", "取消配对");
                    default:
                        break;
                }
            }else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                System.out.println("结束查找");
                if(refresh_icon!=null)
                refresh_icon.showCover();
//                Message msg = handler.obtainMessage();
//                msg.what = 3;
//                handler.sendMessage(msg);
            }else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
                System.out.println("开始查找");
                if(refresh_icon!=null)
                refresh_icon.showAnimation();
            }

        }
    };


//    private void showSerialDataActivity(UsbSerialPort port,int duration) {
//        SerialDataActivity.show(this.getContext(), port,duration);
//    }
    private void showSerialDataActivity(UsbSerialPort port) {
        SerialDataActivity.show(this.getContext(), port);
    }
}
